package com.bsf;

import com.jcraft.jsch.*;

import java.io.*;
import java.util.Scanner;


/**
 * Created by 47279 on 2018/6/15.
 */
public class Main {
    public static void main(String[] args) {
        JSch jsch = null;
        Session session = null;
        Channel channel = null;
        String user="";
        String host="";
        String port="22";
        String pwd="";
        String cmd="";
        //解析
        try {
            String[] logininfo = args[0].replace("@@", "❤❤").split("@");
             user = logininfo[0].replace("❤❤", "@");
             host = logininfo[1];
            if (logininfo[1].contains(":")) {
                String[] tt = logininfo[1].split(":");
                host = tt[0];
                port = tt[1];
            }

            pwd = logininfo[2].replace("❤❤", "@");
            cmd = args[1];
            System.out.println("user:" + user);
            System.out.println("host:" + host);
            System.out.println("port:" + port);
            System.out.println("pwd:" + pwd);
            System.out.println("cmd:" + cmd);
        }
        catch (Exception e)
        {
            System.out.println("[jssh命令解析异常]" + e.getMessage());
            System.out.println(help);
        }
        //连接
        try {
            jsch = new JSch();
            session = jsch.getSession(user, host, Integer.parseInt(port));
            session.setPassword(pwd);
            session.setConfig("StrictHostKeyChecking", "no");
            System.out.println("[author:车江毅,https://gitee.com/chejiangyi/jssh]");
            //session.setUserInfo(null);

            session.connect(10000);   // making a connection with timeout.
        }
        catch (Exception e)
        {
            System.out.println("[jssh连接异常]" + e.getMessage());
            close(session, channel);
        }
        //执行
        try{
            if ("shell".equals(cmd)) {
                channel = session.openChannel("shell");
                channel.setInputStream(System.in);
                channel.setOutputStream(System.out);
                channel.connect(3 * 1000);
                while (true) {
                    if (channel.isClosed()) {
                        System.out.println("[shell执行完毕]");
                        close(session, channel);
                        break;
                    }
                    Thread.sleep(100);
                }
            } else if ("sftp".equals(cmd)) {
                String type = args[2];
                 channel = (ChannelSftp) session.openChannel("sftp");
                 channel.connect();
                if ( "get".equals(type)) {
                    ((ChannelSftp)channel).get(args[3],args[4]);
                    System.out.println("[文件下载完毕]");
                } else if ("put".equals(type)) {
                    File file = new File(args[3]);
                    if(!file.exists())
                        throw new Exception("本地文件不存在");
                    ((ChannelSftp)channel).put(args[3],args[4]);
                    System.out.println("[文件上传完毕]");
                }
                close(session,channel);
            } else
                throw new Exception("无法识别命令!");
        } catch (Exception e) {
            System.out.println("[jssh异常结束]" + e.getMessage());
            close(session, channel);
        }
    }

    private static void close(Session session, Channel channel){
        try {
            if (channel.getOutputStream() != null)
                //channel.getOutputStream().flush();
                channel.getOutputStream().close();
        } catch (Exception e) {
        }
        try {
            if (channel.getInputStream() != null)
                channel.getInputStream().close();
        } catch (Exception e) {
        }
        if (channel != null)
            try {
                channel.disconnect();
            } catch (Exception exp) {
            }
        if (session != null)
            try {
                session.disconnect();
            } catch (Exception exp) {
            }
        System.exit(0);
    }

    private static String help="命令格式:java -jar jssh.jar [用户名]@[ip]:[端口]@[密码] [命令] [命令参数...]\n" +
            "示范:\n" +
            "[用户名] root\n" +
            "[ip]10.200.133.69\n" +
            "[端口]22\n" +
            "[密码]cjy@@2018! （若@为转义，使用@@）\n" +
            "[命令]sftp （枚举:shell,sftp）\n" +
            "[参数]/root/setting.xml /root/setting.xml (根据命令指定参数)\n" +
            "shell命令:\n" +
            "支持 linux shell\n" +
            "sftp命令:\n" +
            "sftp [get(下载)/put(上传)] [来源文件路径 [目标文件路径]";
}
